package com.han.factory.after.config_factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

/**
 * @ClassName CoffeFactory
 * @Description 描述该类的功能
 * @Author duoduo Han
 * @Date 2024/6/4 15:09
 */
public class CoffeeFactory {
    //加载配置文件，获取配置文件中配置的全类名，并创建该类的对象进行存储
    //1. 定义容器对象存储咖啡对象
    private static HashMap<String, Coffee> map = new HashMap<String, Coffee>();

    //2. 加载配置文件,只需要加载一次
    static {
        //2.1 创建properties对象
        Properties properties = new Properties();
        //2.2 利用properties对象加载配置文件
        InputStream is = CoffeeFactory.class.getClassLoader().getResourceAsStream("com/resources/bean.properties");
        try {
            properties.load(is);
            //从properties对象中获取全类名并创建对象
            for (Object key : properties.keySet()) {
                String className = properties.getProperty((String) key);
                //通过反射创建对象
                Class clazz = Class.forName(className);
                Coffee coffee = (Coffee) clazz.newInstance();
                //将名称和对象存储到容器中
                map.put((String) key, coffee);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //根据名称获取对象
    public static Coffee createCoffee(String name) {
        return map.get(name);
    }
}
